

var http = require('http')

var url = require('url')

var ejs = require('ejs')

var mangoClient = require('mongodb').MongoClient

var url = 'mongodb://127.0.0.1:27017'

var app = require('../EJS/Model/router_server')

http.createServer(app).listen(8008)

app.get('/',function (req, res) {
    var msg = '这是数据库的数据啊'

    ejs.renderFile('../EJS/static/index.ejs',{
        'msg': msg
    },function (err,data) {
        if(err) {
            console.log('模板写入失败')
        }else {
            res.send(data)
        }
    })
})

app.get('/add',function (req, res) {

    mangoClient.connect(url, {useNewUrlParser:true}, function (err, client) {

        if (err) {
            console.log('连接数据库失败')
        }else {

            //获取db
            var db = client.db('users')
            db.collection('news').insertOne({
                title: '今日热点',
                newsId: '5555',
                content: '艺人我饮酒醉'
            },function (err, data) {
                if (err) {
                    console.log('添加失败')
                }else {
                    res.send('添加成功')
                    client.close()
                }
            })

        }

    })

})

app.get('search',function (req, res) {
    mangoClient.connect(url,{useNewUrlParser:true},function (err, client) {
        if (err) {
            console.log('连接数据库失败')
        }else {

            var list = [] /*存放数据库数据*/

            //获取db
            var db = client.db('users')
            var result = db.collection('news').find()


            result.toArray(function(err,docs){
                if (err) {

                } else {
                    ejs.renderFile('../EJS/static/index.ejs',{
                        msg:"模板引擎",
                        list: docs
                    },function (err,data) {
                        if (err) {
                            console.log('模板写入失败');
                        } else {
                            console.log('模板写入成功',data)
                            res.send(data)
                            client.close()
                        }
                    })
                }
            });


        }
    })
})
